package com.spider.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spider.constant.FanxingUrl;
import com.spider.entity.FanxingDetailEntity;
import com.spider.entity.FanxingEntity;
import com.spider.mapper.HeownsFanxingMapper;
import com.spider.util.FanxingUtil;
import com.spider.util.HttpTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

/**
 * 繁星
 */
@Service
public class FanxingServiceImpl implements FanxingService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    HeownsFanxingMapper mapper;

    private final Logger logger = LoggerFactory.getLogger(FanxingServiceImpl.class);

    @Override
    public JSONObject createToken(String workNo) throws Exception {
        //拼接参数
        String url= FanxingUrl.PRODUCT_URL+FanxingUrl.TOKEN_URL;
/*        JSONObject jb=new JSONObject(new LinkedHashMap());
        jb.put("fieldValue",FanxingUrl.FIELD_VALUE);*/
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("fieldValue", workNo);
//        System.out.println(jb);
        String result= HttpTokenUtil.postRequest(httpHeaders,url,new JSONObject());
        //String result = restTemplate.postForObject(url,jb,String.class);
        System.out.println(result);
        JSONObject res=JSONObject.parseObject(result);
        if(res!=null){
           return res;
        }
        return null;
    }

    public static void main(String[] args) {
        String a="2023-07-18 15:16:17.0";
        System.out.println();
    }

    /**
     * 添加
     */
    @Override
    public void sendWorkflow() throws Exception {
        //查询主表数据
        List<FanxingEntity> list = mapper.selectByDate();
        if(list==null){
            //logger.info("没有数据直接返回");
        }else{
            logger.info("查询出结果集为:"+list.size());
            for(FanxingEntity entity:list){
                try{
                    //调整字段值 日期可能带.0，如果超过19位则只取19位
                    if(entity.getRq()!=null&&entity.getRq().length()>19){
                        entity.setRq(entity.getRq().substring(0,19));
                    }
                    //拼接参数
                    String url= FanxingUrl.PRODUCT_URL+FanxingUrl.WORKFLOW_URL;
                    JSONObject tokenJb = this.createToken(entity.getSqr());
                    String enUserId= (String) tokenJb.get("enUserId");
                    String userId= (String) tokenJb.get("userId");
                    String token= (String) tokenJb.get("token");
                    HttpHeaders httpHeaders = new HttpHeaders();
                    httpHeaders.add("Accept", "application/json");
                    httpHeaders.add("appid",  "klp");
                    httpHeaders.add("token",  token);
                    httpHeaders.add("userid",  enUserId);
                    httpHeaders.setAccept(Collections.singletonList(MediaType.ALL));
                    httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                    MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
                    String requestName="阿尔塔付款<"+entity.getBh()+">"+entity.getGf();
                    requestBody.add("requestName",requestName);
                    entity.setSqr(userId);
                    JSONArray mainData = FanxingUtil.getMainData(entity);
                    requestBody.add("mainData",mainData.toString());
                    System.out.println("fid值为："+entity.getFid());
                    List<FanxingDetailEntity> listDetails = mapper.selectDetails(entity.getFid());
                    String detailData = FanxingUtil.getDetailData(listDetails);
                    //requestBody.add("mainData","[{\"fieldName\":\"fjsj\",\"fieldValue\":\"发件时间\"},{\"fieldName\":\"fjr\",\"fieldValue\":\"发件人\"},{\"fieldName\":\"bh\",\"fieldValue\":\"编号\"},{\"fieldName\":\"rq\",\"fieldValue\":\"日期\"},{\"fieldName\":\"yj\",\"fieldValue\":\"邮件\"},{\"fieldName\":\"sqr\",\"fieldValue\":\"660\"},{\"fieldName\":\"sqrbh\",\"fieldValue\":\"申请人编号\"},{\"fieldName\":\"je\",\"fieldValue\":\"金额\"},{\"fieldName\":\"ddje\",\"fieldValue\":\"订单金额\"},{\"fieldName\":\"xfje\",\"fieldValue\":\"需付金额\"},{\"fieldName\":\"bb\",\"fieldValue\":\"币别\"},{\"fieldName\":\"zy\",\"fieldValue\":\"摘要\"},{\"fieldName\":\"cgbz\",\"fieldValue\":\"采购备注\"},{\"fieldName\":\"yt\",\"fieldValue\":\"用途\"},{\"fieldName\":\"gf\",\"fieldValue\":\"供方\"},{\"fieldName\":\"hm\",\"fieldValue\":\"户名\"},{\"fieldName\":\"khyx\",\"fieldValue\":\"浙江工商银行\"},{\"fieldName\":\"zh\",\"fieldValue\":\"账号\"},{\"fieldName\":\"bm\",\"fieldValue\":\"采购部\"},{\"fieldName\":\"fkfs\",\"fieldValue\":\"付款方式\"},{\"fieldName\":\"fkqx\",\"fieldValue\":\"付款期限\"},{\"fieldName\":\"pzr\",\"fieldValue\":\"批准人\"},{\"fieldName\":\"pzrq\",\"fieldValue\":\"批准日期\"},{\"fieldName\":\"dkrq\",\"fieldValue\":\"打款日期\"},{\"fieldName\":\"dkje\",\"fieldValue\":\"打款金额\"},{\"fieldName\":\"cny\",\"fieldValue\":\"出纳员\"},{\"fieldName\":\"cwbz\",\"fieldValue\":\"财务备注\"},{\"fieldName\":\"dkpz\",\"fieldValue\":\"打款凭证\"},{\"fieldName\":\"cwsh\",\"fieldValue\":\"财务审核\"},{\"fieldName\":\"cwshrq\",\"fieldValue\":\"财务审核日期\"},{\"fieldName\":\"zfbs\",\"fieldValue\":\"作废标志\"}]")
                    requestBody.add("workflowId","96");
                    System.out.println("detail:"+detailData);
                    requestBody.add("detailData",detailData);
                    System.out.println(requestBody.toString());
                    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, httpHeaders);
                    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
                    System.out.println(response);
                    JSONObject jb=JSONObject.parseObject(response.getBody());
                    String code= (String) jb.get("code");
                    System.out.println("code返回值为："+code);
                    if(code!=null&&code.equals("SUCCESS")){
                        FanxingEntity updateEntity=new FanxingEntity();
                        updateEntity.setFid(entity.getFid());
                        updateEntity.setScbs("1");
                        mapper.updateRecord(updateEntity);
                    }else{
                        FanxingEntity updateEntity=new FanxingEntity();
                        updateEntity.setFid(entity.getFid());
                        updateEntity.setScbs("0");
                        mapper.updateRecord(updateEntity);
                    }
                }catch (Exception e){
                    FanxingEntity updateEntity=new FanxingEntity();
                    updateEntity.setFid(entity.getFid());
                    updateEntity.setScbs("0");
                    mapper.updateRecord(updateEntity);
                }

            }

        }



        //查询结果集 暂时一次只退一条
        /*FanxingEntity entity=new FanxingEntity();
        entity=FanxingUtil.getTestFanxingEntity();
        List<FanxingDetailEntity> list =new ArrayList<>();
        list=FanxingUtil.getTestFanxingDetailEntity();
        if(entity==null){
            logger.info("繁星推送无数据，推送结束");
        }else{
            logger.info("繁星推送查询结果集数量为1");
                try{
                    JSONObject body= FanxingUtil.getBody(entity,list);
                    logger.info("拼接数据结果："+body.toString());
                    MultiValueMap<String, Object> map=new LinkedMultiValueMap<>();
                    map.add("requestName","群星流程测试04");
                    map.add("mainData","");
                    map.add("workflowId","96");
                    map.add("detailData","");
                    String res=HttpTokenUtil.postRequest(httpHeaders,url,map);
                    System.out.println(res);

                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("繁星推送失败，失败原因："+e.getMessage());
                }
            }*/

    }
}
